package zjc.bookkeeping.tools;

import android.util.Log;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import zjc.bookkeeping.db.AccountBean;
import zjc.bookkeeping.db.ConsumptionBean;
import zjc.bookkeeping.db.DBManager;

public class ReadCsv {
    //    读取支付宝导出的csv文件数据
    public static List<ConsumptionBean> readAlipayCsv(String excelPath) {
        List<ConsumptionBean> list = new ArrayList<ConsumptionBean>();
        ConsumptionBean consumptionBean;
        String time;
        int year,month,day;
        File file = new File(excelPath);
        if (!file.exists()){
            file.mkdirs();
        }
        Charset gbk = Charset.forName("GBK");
        InputStreamReader inputStreamReader = null;
        InputStream inputStream = null;
        BufferedReader bufferedReader = null;
        List<String[]> dataList = new ArrayList<>();
        String rowRecord = null;
        try {
            inputStream = new FileInputStream(file);
            inputStreamReader = new InputStreamReader(inputStream,gbk);
            bufferedReader = new BufferedReader(inputStreamReader);
            while ((rowRecord = bufferedReader.readLine()) != null){
                String[] line = rowRecord.split("\\,");
                if (line.length > 5){
                    dataList.add(line);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
//        String str = "";
//        for (int i=0;i<dataList.get(0).length;i++){
//            str += dataList.get(0)[i];
//        }
//        Log.i("str",str);
        int timeIndex = ToolsClass.getStringIndex("交易时间",dataList.get(0));
        int businessIndex = ToolsClass.getStringIndex("交易对方",dataList.get(0));
        int remarksIndex = ToolsClass.getStringIndex("商品说明",dataList.get(0));
        int kindIndex = ToolsClass.getStringIndex("收/支",dataList.get(0));
        int moneyIndex = ToolsClass.getStringIndex("金额",dataList.get(0));
//        Log.i("下标","时间：" + timeIndex+"商家："+businessIndex+"备注："+remarksIndex+"类型："+kindIndex+"金额："+moneyIndex);
        for (int i=1;i<dataList.size();i++){
//            Log.i("数据","时间：" + dataList.get(i)[timeIndex]+"商家："+businessIndex+"备注："+remarksIndex+"类型："+dataList.get(i)[kindIndex]+"金额："+dataList.get(i)[moneyIndex]);
            consumptionBean = new ConsumptionBean();
            if (dataList.get(i)[kindIndex].contains("收入")||dataList.get(i)[kindIndex].contains("支出")){
                if (dataList.get(i)[kindIndex].contains("支出")){
                    consumptionBean.setConsumption_class_name("其他支出");
                    consumptionBean.setConsumption_kind(0);
                }else if (dataList.get(i)[kindIndex].contains("收入")){
                    consumptionBean.setConsumption_class_name("其他收入");
                    consumptionBean.setConsumption_kind(1);
                }
                if (remarksIndex != -1){
                    consumptionBean.setConsumption_remarks(dataList.get(i)[remarksIndex]);
                }
                consumptionBean.setConsumption_money(Float.parseFloat(dataList.get(i)[moneyIndex]));
                if (businessIndex != -1){
                    consumptionBean.setConsumption_business(dataList.get(i)[businessIndex]);
                }
                consumptionBean.setaccount_id(String.valueOf(DBManager.selectAccountId()));
                consumptionBean.setConsumption_method("支付宝");
                Date date = null;
                try {
                    date = new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(dataList.get(i)[timeIndex]);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                SimpleDateFormat timeS = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
                time = timeS.format(date);
                SimpleDateFormat yearS = new SimpleDateFormat("yyyy");
                String yearStr = yearS.format(date);
                year = Integer.parseInt(yearStr);
                SimpleDateFormat monthS = new SimpleDateFormat("MM");
                String monthStr = monthS.format(date);
                month = Integer.parseInt(monthStr);
                SimpleDateFormat dayS = new SimpleDateFormat("dd");
                String dayStr = dayS.format(date);
                day = Integer.parseInt(dayStr);
                consumptionBean.setConsumption_time(time);
                consumptionBean.setConsumption_year(year);
                consumptionBean.setConsumption_month(month);
                consumptionBean.setConsumption_day(day);
                Log.i("succeed "+ i +" 次","name: "+consumptionBean.getConsumption_class_name()+"   remarks: "+consumptionBean.getConsumption_remarks()
                        +"   money: "+consumptionBean.getConsumption_money()+"   business: "+consumptionBean.getConsumption_business()+"   account: "+consumptionBean.getaccount_id()
                        +"   method: "+consumptionBean.getConsumption_method()+"   time: "+consumptionBean.getConsumption_time()+"   year: "+consumptionBean.getConsumption_year()
                        + "   month: "+consumptionBean.getConsumption_month()+"   kind: "+consumptionBean.getConsumption_day()+"数据获取成功！！！");
                list.add(consumptionBean);
            }
        }
        return list;
    }
    //    读取微信导出的csv文件数据
    public static List<ConsumptionBean> readWechatCsv(String excelPath){
        List<ConsumptionBean> list = new ArrayList<ConsumptionBean>();
        ConsumptionBean consumptionBean;
        String time;
        int year,month,day;
        File file = new File(excelPath);
        if (!file.exists()){
            file.mkdirs();
        }
        Charset gbk = Charset.forName("UTF-8");
        InputStreamReader inputStreamReader = null;
        InputStream inputStream = null;
        BufferedReader bufferedReader = null;
        List<String[]> dataList = new ArrayList<>();
        String rowRecord = null;
        try {
            inputStream = new FileInputStream(file);
            inputStreamReader = new InputStreamReader(inputStream,gbk);
            bufferedReader = new BufferedReader(inputStreamReader);
            while ((rowRecord = bufferedReader.readLine()) != null){
                String[] line = rowRecord.split("\\,");
                if (line.length > 5){
                    dataList.add(line);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
//        String str = "";
//        for (int i=0;i<dataList.get(0).length;i++){
//            str += dataList.get(0)[i];
//        }
//        Log.i("str",str);
        int timeIndex = ToolsClass.getStringIndex("交易时间",dataList.get(0));
        int businessIndex = ToolsClass.getStringIndex("交易对方",dataList.get(0));
        int remarksIndex = ToolsClass.getStringIndex("商品",dataList.get(0));
        int kindIndex = ToolsClass.getStringIndex("收/支",dataList.get(0));
        int moneyIndex = ToolsClass.getStringIndex("金额",dataList.get(0));
//        Log.i("下标","时间：" + timeIndex+"商家："+businessIndex+"备注："+remarksIndex+"类型："+kindIndex+"金额："+moneyIndex);
        for (int i=1;i<dataList.size();i++){
//            Log.i("数据","时间：" + dataList.get(i)[timeIndex]+"商家："+businessIndex+"备注："+remarksIndex+"类型："+dataList.get(i)[kindIndex]+"金额："+dataList.get(i)[moneyIndex]);
            consumptionBean = new ConsumptionBean();
            if (dataList.get(i)[kindIndex].contains("收入")||dataList.get(i)[kindIndex].contains("支出")){
                if (dataList.get(i)[kindIndex].contains("支出")){
                    consumptionBean.setConsumption_class_name("其他支出");
                    consumptionBean.setConsumption_kind(0);
                }else if (dataList.get(i)[kindIndex].contains("收入")){
                    consumptionBean.setConsumption_class_name("其他收入");
                    consumptionBean.setConsumption_kind(1);
                }
                if (remarksIndex != -1){
                    consumptionBean.setConsumption_remarks(dataList.get(i)[remarksIndex]);
                }
                consumptionBean.setConsumption_money(Float.parseFloat(dataList.get(i)[moneyIndex].substring(1)));
                if (businessIndex != -1){
                    consumptionBean.setConsumption_business(dataList.get(i)[businessIndex]);
                }
                consumptionBean.setaccount_id(String.valueOf(DBManager.selectAccountId()));
                consumptionBean.setConsumption_method("微信");
                Date date = null;
                try {
                    date = new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(dataList.get(i)[timeIndex]);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                SimpleDateFormat timeS = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
                time = timeS.format(date);
                SimpleDateFormat yearS = new SimpleDateFormat("yyyy");
                String yearStr = yearS.format(date);
                year = Integer.parseInt(yearStr);
                SimpleDateFormat monthS = new SimpleDateFormat("MM");
                String monthStr = monthS.format(date);
                month = Integer.parseInt(monthStr);
                SimpleDateFormat dayS = new SimpleDateFormat("dd");
                String dayStr = dayS.format(date);
                day = Integer.parseInt(dayStr);
                consumptionBean.setConsumption_time(time);
                consumptionBean.setConsumption_year(year);
                consumptionBean.setConsumption_month(month);
                consumptionBean.setConsumption_day(day);
                list.add(consumptionBean);
            }
        }
        return list;
    }
//导出本地账单的csv文件
    public static void exportCsv(String filePath) {
        List<ConsumptionBean> consumptionBeanList = new ArrayList<>();
        consumptionBeanList = DBManager.getAllAccountConsumption(String.valueOf(DBManager.selectAccountId()),"全部","");
        BufferedWriter bufferedWriter;
        File file = new File(filePath);
        FileOutputStream fileOutputStream = null;
        OutputStreamWriter outputStreamWriter = null;
        try{
            fileOutputStream = new FileOutputStream(file);
            outputStreamWriter = new OutputStreamWriter(fileOutputStream,"GBK");
            bufferedWriter = new BufferedWriter(outputStreamWriter);
            AccountBean accountBean = DBManager.getAccountById(DBManager.selectAccountId());
            String str = "账本名："+accountBean.getAccount_name();
            bufferedWriter.write(str);
            bufferedWriter.newLine();
            str = "支出金额："+accountBean.getAccount_outcome();
            bufferedWriter.write(str);
            bufferedWriter.newLine();
            str = "收入金额："+accountBean.getAccount_income();
            bufferedWriter.write(str);
            bufferedWriter.newLine();
            str = "一共有："+accountBean.getAccount_item()+"条记录。";
            bufferedWriter.write(str);
            bufferedWriter.newLine();
            str = "账本创建时间："+accountBean.getAccount_time();
            bufferedWriter.write(str);
            bufferedWriter.newLine();
            bufferedWriter.write("收/支"+",");
            bufferedWriter.write("交易类型"+",");
            bufferedWriter.write("备注"+",");
            bufferedWriter.write("金额"+",");
            bufferedWriter.write("商家"+",");
            bufferedWriter.write("账户"+",");
            bufferedWriter.write("时间");
            bufferedWriter.newLine();
            for (int i=0;i<consumptionBeanList.size();i++){
                switch (consumptionBeanList.get(i).getConsumption_kind()){
                    case 0:
                        bufferedWriter.write("支出"+",");
                        break;
                    case 1:
                        bufferedWriter.write("收入"+",");
                        break;
                    case 2:
                        bufferedWriter.write("转账"+",");
                        break;
                }
                bufferedWriter.write(consumptionBeanList.get(i).getConsumption_class_name()+",");
                bufferedWriter.write(consumptionBeanList.get(i).getConsumption_remarks()+",");
                bufferedWriter.write(consumptionBeanList.get(i).getConsumption_money()+",");
                bufferedWriter.write(consumptionBeanList.get(i).getConsumption_business()+",");
                bufferedWriter.write(consumptionBeanList.get(i).getConsumption_method()+",");
                bufferedWriter.write(consumptionBeanList.get(i).getConsumption_time());
                bufferedWriter.newLine();
                Log.i("succeed "+ i +" 次","name: "+consumptionBeanList.get(i).getConsumption_class_name()+"   remarks: "+consumptionBeanList.get(i).getConsumption_remarks()
                        +"   money: "+consumptionBeanList.get(i).getConsumption_money()+"   business: "+consumptionBeanList.get(i).getConsumption_business()+"   account: "+consumptionBeanList.get(i).getaccount_id()
                        +"   method: "+consumptionBeanList.get(i).getConsumption_method()+"   time: "+consumptionBeanList.get(i).getConsumption_time()+"数据导出成功！！！");
            }
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStreamWriter.close();
            fileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
//读取本地导出的csv文件
    public static List<ConsumptionBean> importCSv(String excelPath) {
        List<ConsumptionBean> list = new ArrayList<ConsumptionBean>();
        ConsumptionBean consumptionBean;
        String time;
        int year,month,day;
        File file = new File(excelPath);
        if (!file.exists()){
            file.mkdirs();
        }
        Charset gbk = Charset.forName("GBK");
        InputStreamReader inputStreamReader = null;
        InputStream inputStream = null;
        BufferedReader bufferedReader = null;
        List<String[]> dataList = new ArrayList<>();
        String rowRecord = null;
        try {
            inputStream = new FileInputStream(file);
            inputStreamReader = new InputStreamReader(inputStream,gbk);
            bufferedReader = new BufferedReader(inputStreamReader);
            while ((rowRecord = bufferedReader.readLine()) != null){
                String[] line = rowRecord.split("\\,");
                if (line.length > 5){
                    dataList.add(line);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        int kindIndex = ToolsClass.getStringIndex("收/支",dataList.get(0));
        int consumptionClassIndex = ToolsClass.getStringIndex("交易类型",dataList.get(0));
        int remarksIndex = ToolsClass.getStringIndex("备注",dataList.get(0));
        int moneyIndex = ToolsClass.getStringIndex("金额",dataList.get(0));
        int businessIndex = ToolsClass.getStringIndex("商家",dataList.get(0));
        int methodIndex = ToolsClass.getStringIndex("账户",dataList.get(0));
        int timeIndex = ToolsClass.getStringIndex("时间",dataList.get(0));
        for (int i=1;i<dataList.size();i++){
            consumptionBean = new ConsumptionBean();
            if (dataList.get(i)[kindIndex].contains("支出")){
                consumptionBean.setConsumption_kind(0);
            }else if (dataList.get(i)[kindIndex].contains("收入")){
                consumptionBean.setConsumption_kind(1);
            }else if (dataList.get(i)[kindIndex].contains("转账")){
                consumptionBean.setConsumption_kind(2);
            }
            consumptionBean.setConsumption_class_name(dataList.get(i)[consumptionClassIndex]);
            consumptionBean.setConsumption_remarks(dataList.get(i)[remarksIndex]);
            consumptionBean.setConsumption_money(Float.parseFloat(dataList.get(i)[moneyIndex]));
            consumptionBean.setConsumption_business(dataList.get(i)[businessIndex]);
            consumptionBean.setaccount_id(String.valueOf(DBManager.selectAccountId()));
            consumptionBean.setConsumption_method(dataList.get(i)[methodIndex]);
            Date date = null;
            try {
                date = new SimpleDateFormat("yyyy年MM月dd日 HH:mm").parse(dataList.get(i)[timeIndex]);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            SimpleDateFormat timeS = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
            time = timeS.format(date);
            SimpleDateFormat yearS = new SimpleDateFormat("yyyy");
            String yearStr = yearS.format(date);
            year = Integer.parseInt(yearStr);
            SimpleDateFormat monthS = new SimpleDateFormat("MM");
            String monthStr = monthS.format(date);
            month = Integer.parseInt(monthStr);
            SimpleDateFormat dayS = new SimpleDateFormat("dd");
            String dayStr = dayS.format(date);
            day = Integer.parseInt(dayStr);
            consumptionBean.setConsumption_time(time);
            consumptionBean.setConsumption_year(year);
            consumptionBean.setConsumption_month(month);
            consumptionBean.setConsumption_day(day);
            list.add(consumptionBean);
        }
        return list;
    }
}
